package com.tjhk.netty.util;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

/**
 * 协议常用工具
 */
public class ProtocolUtil {
    /**
     * 校验BCC校验位
     * @param buf
     * @return
     */
    public static boolean verifyBcc(ByteBuf buf) {
        System.out.println(ByteBufUtil.hexDump(buf));
        byte checkCode = buf.getByte(buf.readableBytes() - 1);
        buf = buf.slice(0, buf.readableBytes() - 1);
        byte calculatedCheckCode = bcc(buf);
        return checkCode == calculatedCheckCode;
    }
    /**
     * 生成BCC校验位(异或校验)
     */
    public static byte bcc(ByteBuf byteBuf) {
        byte cs = 0;
        while (byteBuf.isReadable())
            cs ^= byteBuf.readByte();
        byteBuf.resetReaderIndex();
        return cs;
    }
    /**
     * 添加BCC校验位(异或校验)
     */
    public static void addBcc(ByteBuf byteBuf) {
        Byte bcc = bcc(byteBuf);
        byteBuf.writeByte(bcc);
    }
    /**
     * 添加分隔符
     * @param input
     * @param bytes
     * @return
     */
    public static ByteBuf addDelimiter(ByteBuf input,byte[] bytes){
        ByteBuf output = Unpooled.buffer(32);
        output.writeBytes(bytes);
        output.writeBytes(input);
        output.writeBytes(bytes);
        return output;
    }
}
